package com.topteam.component.freemarker;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import com.topteam.frame.controllor.BaseController;
import com.topteam.utility.StringUtil;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 带有权限控制显隐的按钮
 * @author Jiang Feng
 *
 */
public class TopBoolCheckbox extends TopTemplateModel{
	
	public static final String TAG = "boolCheckbox";
	
	private BaseController controller;
	
	private String id;
	
	private String text;
	
	private String onclick;
	
	private String name;
	
	private boolean checked;
	
	private boolean value;
	
	private String onchange;
	
	public TopBoolCheckbox(BaseController controller){
		this.controller = controller;
	}
	
	private void initPara(Map para, Environment env) throws TemplateException{
		id = getStrPara("id", para, env);
		if(StringUtil.isNull(id)){
			throw new TemplateException("必须直接按钮id的值", env);
		}
		text = getStrPara("text", para, env);
		onclick = getStrPara("onclick", para, env);
		onchange = getStrPara("onchange", para, env);
		value = getBoolPara("value", para, env,value);
		name = getStrPara("name", para, env);
		checked = getBoolPara("checked", para, env,value) | value;
	}

	@Override
	public void execute(Environment env, Map para, TemplateModel[] arg2,
			TemplateDirectiveBody arg3) throws TemplateException, IOException {
		initPara(para,env);
		Writer w = env.getOut();
		w.write("<input id=\""+id+"\" type=\"checkbox\" ");
		if(checked)
			w.write("checked=\""+String.valueOf(checked)+"\"");
		w.write(" onchange=\"javascript:$('#"+id+"-value').val(this.checked);"+onchange+"\">");
		if(StringUtil.isNotNull(text))
			w.write(text);
		w.write("</input>");
		if(StringUtil.isNotNull(name)){
			w.write("<input id='"+id+"-value' type='hidden' name='"+name+"'>");
		}
		//writeScript(w);
	}
	
	public void writeScript(Writer w) throws IOException{
		w.write("<script type=\"text/javascript\">");
		
		w.write("</script>");
	}

	
}
